<template>
  <div class="address-manage">
    <i class="new-content2-back el-icon-arrow-left" @click="backDui"></i>

    <!-- <div class="new-title" style="margin-top:-10px;">
      快递邮寄
    </div> -->
    <template v-if="step == 1">
      <div class="new-content">
        <div class="new-title" @click="goAddressManage">
          地址管理
          <i class="new-title-icon el-icon-arrow-right"></i>
        </div>
        <div class="new-form-main">
          <el-form ref="form" :model="addressData2" labelPosition="left" label-width="80px">
            <el-form-item label="收货人">
              <el-input disabled :value="addressData2.consignee"></el-input>
            </el-form-item>
            <el-form-item label="手机号码">
              <el-input disabled :value="addressData2.phoneNumber"></el-input>
            </el-form-item>
            <el-form-item label="所在地区">
              <el-input disabled :value="addressData2.region"></el-input>
            </el-form-item>
            <el-form-item label="详细地址">
              <el-input type="textarea" disabled :value="addressData2.detailedAddress"></el-input>
            </el-form-item>
            <!-- <el-form-item label="详细地址">
                  <el-radio-group v-model="activityForm.addresss">
                    <el-radio :label="3">备选项</el-radio>
                    <el-radio :label="1">备选项</el-radio>
                    <el-radio :label="2">备选项</el-radio>
                  </el-radio-group>
                </el-form-item> -->
          </el-form>
        </div>
      </div>
      <div class="new-btn" @click="affirm()">确定</div>
    </template>
    <template v-if="step == 2">
      <div class="new-content2">
        <div class="new-title" style="    margin-top: 0px;">
          <div class="new-title-left">地址管理</div>
          <div class="new-title-btn" @click="addForm">
            添加收货地址
          </div>
        </div>
        <div class="new-list">
          <div class="new-item" v-for="item in addressList" @click="addForm(item)" :key="item.id">
            <div class="new-item-title">
              <span>{{ item.consignee }}</span><span>{{ item.phoneNumber }}</span>
            </div>
            <div class="new-item-content">
              <div class="new-item-content-left">
                <span>{{ item.region }}</span>
                <span>{{ item.detailedAddress || "" }}</span>
              </div>
              <div class="new-item-content-right">
                <div @click.stop="setDefault(item)" style="display: flex;align-items: center;margin-left: -24px;">
                  <!-- .new-item -->
                  <div class="box-check invite" style="line-height: 24px;margin-right:4px;">
                    <el-checkbox v-model="item.choose"></el-checkbox>
                  </div>
                  <span :style="item.whetherDefault == 1 ? 'color:#64B6A8' : 'color:#333333'
                    ">设为默认</span>
                </div>

                <span @click.stop="del(item)">删除</span>
              </div>
            </div>

          </div>
        </div>
        <el-empty desc="暂无数据" v-if="addressList.length == 0"> </el-empty>
      </div>
    </template>
    <el-dialog class="mask" :visible.sync="showMask" append-to-body width="30%" fullscreen>
      <div class="mask" @click.self.stop="showMask = false">
        <div class="mask-box">
          <div class="mask-close el-icon-close" @click="close"></div>
          <div class="mask-title">
            添加收货地址
          </div>
          <div class="new-form-main">
            <el-form ref="form" :model="activityAddForm" labelPosition="left" label-width="80px">
              <el-form-item label="收货人">
                <el-input v-model="activityAddForm.consignee" placeholder="请输入收货人"></el-input>
              </el-form-item>
              <el-form-item label="手机号码">
                <el-input v-model="activityAddForm.phoneNumber" placeholder="请输入手机号码"></el-input>
              </el-form-item>
              <el-form-item label="所在地区">
                <el-input v-model="activityAddForm.region" placeholder="请输入所在地区"></el-input>
                <!-- <el-cascader
                  :options="addressData"
                  :disabled="false"
                  @change="handleAddress"
                  style="width: 100%"
                  v-model="addressSelections"
                  placeholder="请选择省市区"
                ></el-cascader> -->

                <!-- <el-select
                  style="width:100%;"
                  v-model="activityAddForm.region"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    :disabled="item.disabled"
                  >
                  </el-option>
                </el-select> -->
              </el-form-item>
              <el-form-item label="详细地址">
                <el-input type="textarea" placeholder="请输入地址" v-model="activityAddForm.detailedAddress"></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="new-btn" style="width:100px;margin:28px auto;width: 190px;height: 40px;line-height: 40px;"
            @click.stop="shippAddressData">
            保存
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// provinceAndCityData是省市二级联动数据（不带“全部”选项）
// regionData是省市区三级联动数据（不带“全部”选项）
// provinceAndCityDataPlus是省市区三级联动数据（带“全部”选项）
// regionDataPlus是省市区三级联动数据（带“全部”选项）
// “全部"选项绑定的value是空字符串”"
// CodeToText是个大对象，属性是区域码，属性值是汉字 用法例如：CodeToText[‘110000’]输出北京市
// extToCode是个大对象，属性是汉字，属性值是区域码
// 用法例如：TextToCode[‘北京市’].code输出110000,TextToCode[‘北京市’][‘市辖区’].code输出110100,TextToCode[‘北京市’][‘市辖区’][‘朝阳区’].code输出110105

import {
  provinceAndCityData,
  regionData,
  provinceAndCityDataPlus,
  regionDataPlus,
  CodeToText,
  TextToCode
} from "element-china-area-data";
export default {
  computed: {
    addressData() {
      return regionData;
    }
  },
  props: {
    obj: {
      type: Object,
      default() {
        return {};
      }
    }
  },
  watch: {
    activityAddForm: {
      handler(newV, oldV) {
        if (!(newV || {}).id) {
          localStorage.setItem("activityAddForm", JSON.stringify(newV));
        }
      },
      deep: true
    }
  },
  data() {
    return {
      addressSelections: [],
      activityAddForm: {
        consignee: "",
        phoneNumber: "",
        region: "",
        detailedAddress: ""
      },

      showMask: false,
      step: 1,
      activityForm: { name: "", phone: "", region: "", addresss: "1" },
      options: [],
      item: {},
      user: {},
      loading: false,
      addressData2: {}, //默认地址
      addressList: [] //地址列表
    };
  },
  created() {
    var user = JSON.parse(localStorage.getItem("userInfo"));
    if (user) {
      this.user = user;
      this.userInfo = user;
      this.defaultAddress();
    }
  },
  methods: {
    affirm() {
      // this.obj
      let obj = JSON.parse(JSON.stringify(this.obj));
      if (!this.addressData2.id) {
        this.myErrorMessage("暂无地址，请前往地址管理中添加地址！");
        return false;
      }
      obj.consignee = this.addressData2.consignee;
      obj.phoneNumber = this.addressData2.phoneNumber;
      obj.region = this.addressData2.region;
      obj.detailedAddress = this.addressData2.detailedAddress;
      // console.log(JSON.stringify(obj, null, 2));

      if (this.submitLoading) {
        return false;
      }
      this.submitLoading = true;

      this.$postHttp("/api/mobile/public/addExchangeRecords", obj).then(res => {
        // this.mySuccessMessage(res.msg);
        this.$postHttp("/api/mobile/public/confirmRedemption", {
          id: res.ExchangeRecordsId,
          userId: this.userInfo.id
        }).then(res => {
          this.mySuccessMessage(res.msg);
          this.$emit("back");
          setTimeout(() => {
            this.submitLoading = false;
          }, 50);

        })

      });
    },
    backDui() {
      if (this.step == 1) {
        this.$emit("back");
      } else if (this.step == 2) {
        this.defaultAddress();
      }
    },
    // 获取默认地址
    defaultAddress() {
      this.$getHttp("/api/mobile/public/getDefaultHarvestAddress", {
        userId: this.userInfo.id
      }).then(res => {
        this.addressData2 = res.defaultHarvestAddress || {};
        this.step = 1;
      });
    },
    // 设置默认地址
    setDefault(item) {
      if (this.setLoading) {
        return
      }
      this.setLoading = true
      this.$postHttp("/api/mobile/public/setDefaultHarvestAddress", {
        userId: this.userInfo.id,
        id: item.id
      }).then(res => {
        this.mySuccessMessage(res.msg);
        this.shippAddressList();
      });
    },
    // 删除此地址
    async del(item) {
      const confirmRes = await this.$confirm("确定删除此地址吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).catch(err => err); //用catch来捕获错误消息
      if ("confirm" === confirmRes) {
        this.$postHttp("/api/mobile/public/deleteHarvestAddress", {
          ids: item.id
        }).then(res => {
          this.mySuccessMessage(res.msg);
          setTimeout(() => {
            this.shippAddressList();
          }, 1000);
        });
      }
    },
    // 获取地址列表
    shippAddressList() {
      this.$getHttp("/api/mobile/public/getMyHarvestAddressTabulation", {
        userId: this.userInfo.id
      }).then(res => {
        if (res.harvestAddressTabulation.length == 1) {
          this.$postHttp("/api/mobile/public/setDefaultHarvestAddress", {
            userId: this.userInfo.id,
            id: res.harvestAddressTabulation[0].id
          }).then(res2 => {
            res.harvestAddressTabulation.map(item => {
              item.choose = true
            })


            this.addressList = res.harvestAddressTabulation;
            this.step = 2;
          });
        } else {
          (res.harvestAddressTabulation || []).map(item => {
            item.choose = item.whetherDefault == 1
          })
          // console.log('addressList1', res.harvestAddressTabulation)
          this.addressList = res.harvestAddressTabulation;
          this.step = 2;
        }
        this.setLoading = false

        this.showMask = false;
        // this.mySuccessMessage(res.msg);
      });
    },
    handleAddress(ele) {
      console.log("eleeleele", ele);
      return;
      for (let i = 0; i < this.addressSelections.length; i++) {
        if (i == 0) {
          this.form.province = CodeToText[this.addressSelections[i]];
        }
        if (i == 1) {
          this.form.city = CodeToText[this.addressSelections[i]];
        }
        if (i == 2) {
          this.form.town = CodeToText[this.addressSelections[i]];
        }
      }
    },
    getAddressInfo() {
      this.addressSelections = [];
      this.form.provinceCode = this.form.province
        ? TextToCode[this.form.province].code
        : "";
      this.form.cityCode = this.form.city
        ? TextToCode[this.form.province][this.form.city].code
        : "";
      this.form.townCode = this.form.town
        ? TextToCode[this.form.province][this.form.city][this.form.town].code
        : "";
      this.addressSelections.push(this.form.provinceCode);
      this.addressSelections.push(this.form.cityCode);
      this.addressSelections.push(this.form.townCode);
    },
    // 地址管理
    goAddressManage() {
      this.shippAddressList();
    },
    shippAddressData() {
      this.activityAddForm.userId = this.userInfo.id;
      if (!this.activityAddForm.consignee) {
        this.myErrorMessage("请填写收货人姓名");
        return false;
      }
      if (!this.activityAddForm.phoneNumber) {
        this.myErrorMessage("请填写收货人手机号");
        return false;
      }
      if (!this.activityAddForm.region) {
        this.myErrorMessage("请填写收货人地址");
        return false;
      }
      this.$postHttp(
        "/api/mobile/public/addOrModifyHarvestAddress",
        this.activityAddForm
      ).then(res => {
        this.mySuccessMessage(res.msg);
        this.shippAddressList();

        this.activityAddForm = {
          consignee: "",
          phoneNumber: "",
          region: "",
          detailedAddress: ""
        };
        localStorage.removeItem("activityAddForm");
      });
    },
    addForm(item = {}) {
      // this.set;
      if (item.id) {
        this.activityAddForm = Object.assign({}, this.activityAddForm, item);
      } else {
        if (JSON.parse(localStorage.getItem("activityAddForm"))) {
          this.activityAddForm = Object.assign(
            {},
            this.activityAddForm,
            JSON.parse(localStorage.getItem("activityAddForm"))
          );
        } else {
          this.activityAddForm = {
            consignee: "",
            phoneNumber: "",
            region: "",
            detailedAddress: ""
          };
        }
      }
      console.log("this.activityAddForm", this.activityAddForm);
      this.showMask = true;
    },
    close() {
      this.showMask = false;
    }
  }
};
</script>

<style lang="less" scoped>
/deep/ .el-dialog {
  background: rgba(0, 0, 0, 0.2);

  .el-dialog__header {
    display: none;
  }

  .el-dialog__body {
    padding: 0;
  }
}

/deep/ .new-content2-back {
  cursor: pointer;
  position: absolute;
  top: -114px;
  left: -164px;
  font-size: 24px;
}

.mask {
  .mask-box {
    box-sizing: border-box;

    display: inline-block;
    padding: 20px 35px 20px 35px;
    text-align: left;
    background: #ffffff;
    border-radius: 10px 10px 10px 10px;
    opacity: 1;
    font-size: 24px;
    font-weight: 400;
    color: #333333;
    line-height: 34px;
    width: 432px;

    position: absolute;
    top: 50%;
    transform: translate(-50%, -50%);
    left: 50%;

    .mask-close {
      position: absolute;
      color: #999999;
      top: 10px;
      right: 10px;
      font-size: 26px;
      cursor: pointer;
    }

    .mask-title {
      text-align: center;
      font-size: 24px;
      font-weight: 400;
      color: #333333;
      line-height: 28px;
      margin-bottom: 40px;
    }

    .mask-btn-wrap {
      .mask-btn {
        width: 284px;
        height: 50px;
        border-radius: 6px 6px 6px 6px;
        opacity: 1;
        border: 1px solid #64b6a8;
        margin: 0 auto;
        text-align: center;
        font-size: 24px;
        font-weight: 400;
        color: #64b6a8;
        line-height: 50px;
        margin-top: 20px;
        cursor: pointer;
      }
    }
  }
}

.address-manage {
  position: relative;

  .new-content2 {
    width: 480px;
    min-height: 322px;
    box-sizing: border-box;
    padding: 20px;
    border: 1px solid #dcdcdc;
    margin-bottom: 20px;

    .new-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .new-title-left {
        font-weight: 500;
        font-size: 20px;
        line-height: 28px;
        color: #333333;
      }

      .new-title-btn {
        cursor: pointer;
        width: 106px;
        height: 28px;
        line-height: 28px;
        text-align: center;
        background: #64b6a8;
        border-radius: 6px;
        font-weight: 400;
        font-size: 16px;
        color: #ffffff;
      }
    }

    .new-list {
      .new-item {
        cursor: pointer;
        padding: 12px 0;
        border-bottom: 1px solid #dcdcdc;
        padding-left: 42px;

        .new-item-title {
          font-weight: 400;
          font-size: 20px;
          line-height: 28px;
          color: #333333;
        }

        .new-item-content {
          display: flex;
          // justify-content: space-between;
          // align-items: center;
          flex-direction: column;
          font-weight: 400;
          font-size: 20px;
          color: #999999;
          margin-top: 8px;

          .new-item-content-left {
            span {
              margin-right: 12px;

              &:last-child {
                margin-right: 0;
              }
            }
          }

          .new-item-content-right {
            flex: 1;
            margin-top: 6px;
            display: flex;
            justify-content: space-between;
            font-size: 17px;

            span {
              cursor: pointer;
              margin-right: 12px;

              &:last-child {
                color: #333333;
                margin-right: 0;
              }
            }
          }
        }
      }
    }
  }
}

.new-title {
  margin-top: 30px;
  height: 34px;
  font-size: 24px;
  font-weight: 500;
  color: #333333;
  line-height: 34px;
}

.new-content {
  // width: 480px;
  // height: 322px;
  border-radius: 0px 0px 0px 0px;
  opacity: 1;
  border: 1px solid #dcdcdc;
  padding: 11px 26px 0 26px;

  .new-title {
    cursor: pointer;
    padding-top: 0;
    padding-left: 32px;
    height: 42px;
    background: #f2f2f2;
    border-radius: 0px 0px 0px 0px;
    opacity: 1;
    margin-bottom: 20px;
    font-size: 18px;
    font-family: PingFang SC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 42px;
    display: flex;
    justify-content: space-between;

    .new-title-icon {
      line-height: 42px;
      font-size: 20px;
      font-weight: 600;
    }
  }
}

.new-btn {
  width: 480px;
  height: 50px;
  background: #64b6a8;
  border-radius: 6px 6px 6px 6px;
  opacity: 1;
  text-align: center;
  font-size: 20px;
  font-weight: 500;
  color: #ffffff;
  line-height: 50px;
  margin-top: 36px;
  margin-bottom: 72px;
  cursor: pointer;
}

.new-form-main {
  margin-bottom: 20px;

  /deep/ .el-form-item {
    margin-bottom: 10px;
  }

  /deep/ .el-input--suffix .el-input__inner {
    // border: 1px solid #c3f8ef;
    border: 1px solid #dcdfe6;
  }

  /deep/ textarea::placeholder {
    color: #cdced1;
    font-size: 14px;
    font-weight: normal;
  }

  /deep/ input::placeholder {
    color: #cdced1;
    font-size: 14px;
    font-weight: normal;
  }
}
</style>
